// Server.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Server.h"
#include <afxsock.h>
#include <vector>
#include <iostream>
#include "ServerProc.h"
#include <conio.h>
using namespace std;

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// The one and only application object

CWinApp theApp;

using namespace std;

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;
	ServerProc p;

	HMODULE hModule = ::GetModuleHandle(NULL);

	if (hModule != NULL)
	{
		// initialize MFC and print and error on failure
		if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
		{
			// TODO: change error code to suit your needs
			_tprintf(_T("Fatal Error: MFC initialization failed\n"));
			nRetCode = 1;
		}
		else
		{
			int n;
			int k = 0;
			// TODO: code your application's behavior here.
			cout << "Nhap so nguoi choi can de thuc hien tro choi: ";
			cin >> n;
			CSocket server;
			CSocket *s = new CSocket[n];
			//Array nickname
			char** nick;
			nick = new char*[n];
			char** buff;
			buff = new char*[n];
			for(int i = 0; i < n; i++)
			{
				nick[i] = new char[100];
				buff[i] = new char[100];
			}
			//Initsocket
			AfxSocketInit(NULL);
			//Tao socket
			server.Create(1234);
			//Lang nghe ket noi tu cac client
			server.Listen(n);
			//Chap nhan ket noi
			for(int t= 0; t < n; t++)
			{
				server.Accept(s[t]);
			}
			for(int t= 0; t < n;t++ )
			{
				s[t].Receive(buff[t],100,0);
				buff[strlen(buff[t])] = 0;

				int number = 0;
				bool temp = p.nickNameProc(buff[t],nick,t);
				number = (int)temp * (t+1);
				s[t].Send((char*)&number,sizeof(int),0);
				if(temp == true)
				{
					nick[k] = buff[t];
					cout << "1 nguoi choi da dang ky thanh cong!"<< endl;
					k++;
				}
				else
				{
					t--;
				}
			}
			//server.Close();
			for(int i = 0; i < n; i++)
			{
				nick[i] = NULL;
				buff[i] = NULL;
			}
			nick = NULL;
			buff = NULL;
		}
	}
	else
	{
		// TODO: change error code to suit your needs
		_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
		nRetCode = 1;
	}

	return nRetCode;
}
